package com.gitee.ixtf.rsocket.agent

import com.gitee.ixtf.guice.Jguice
import com.gitee.ixtf.guice.kotlinx.get
import com.gitee.ixtf.rsocket.BrokerAuth
import com.gitee.ixtf.rsocket.IBrokerAgent
import com.gitee.ixtf.rsocket.kotlinx.buffer
import com.gitee.ixtf.rsocket.kotlinx.payload
import com.gitee.ixtf.rsocket.service.PONG
import com.gitee.ixtf.rsocket.service.PingRequest
import io.vertx.ext.auth.authentication.Credentials
import io.vertx.ext.auth.authentication.TokenCredentials
import io.vertx.ext.auth.jwt.JWTAuth
import io.vertx.kotlin.core.json.jsonObjectOf
import io.vertx.kotlin.ext.auth.jwtOptionsOf
import java.nio.charset.StandardCharsets.UTF_8

open class BrokerClientAgent : RSocketAgent(), IBrokerAgent {
  override suspend fun buildCredentials(): Credentials {
    val claims = jsonObjectOf("sub" to "client")
    val options = jwtOptionsOf(expiresInMinutes = 5)
    val token = Jguice.get<JWTAuth>(BrokerAuth::class.java).generateToken(claims, options)
    return TokenCredentials(token)
  }

  override suspend fun ping(route: String): Boolean =
      PONG ==
          requestResponse {
                val event = PingRequest.cloudEvent("client")
                event.payload(route)
              }
              .buffer()
              .toString(UTF_8)
}
